//
//  MTTopUpHistoryListController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/8.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result

class MTTopUpHistoryListController: BaseViewController {
    
    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        let provider = MTProvider<MineApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private let disposeBag = DisposeBag()
    
    private var result: [MTRedPacketReportSubModel] = []
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .grouped)
        table.delegate = self
        table.dataSource = self
        table.register(TopUpHistoryListCell.self, forCellReuseIdentifier: TopUpHistoryListCell.reuseIdentity())
        table.separatorInset = UIEdgeInsets.zero
        table.tableFooterView = UIView()
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        table.backgroundColor = UIColor.theme.background
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadFirst()

        }
        return table
    }()
    
    override func refreshView() {
        loadFirst()
    }
    
    private func loadData(loadMore: Bool) {
        provider.rx.requestResult(.rechargeList(currentPage)).subscribe(onNext: { [weak self] (result:Result<MTRedPacketReportModel, AnyError> , isCache:Bool) in
            guard let weakSelf = self else { return }
            switch result {
            case .success(let model):
                if model.code == 200 {
                    weakSelf.tableView.mj_footer?.endRefreshing()
                    weakSelf.tableView.mj_header?.endRefreshing()
                    if weakSelf.currentPage == 1 {
                        weakSelf.tableView.mj_footer?.state = .idle
                    }
                    
                    if let r = model.result {
                        if (model.page?.pages == weakSelf.currentPage) {
                            weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                        if loadMore == true {
                            weakSelf.result = weakSelf.result + r
                        } else {
                            weakSelf.result = r
                        }
                        
                        weakSelf.hiddenHF(isHidden: weakSelf.result.count == 0)
                    } else {
                        weakSelf.hiddenHF(isHidden: true)
                    }
                    
                    DispatchQueue.main.async {
                        weakSelf.tableView.reloadData()
                    }
                }
                break
            case .failure( _):
                
                break
            }
            
        }).disposed(by: globalDisposedBag)
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    @objc private func loadFirst() {
        self.currentPage = 1
        
        loadData(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadData(loadMore: true)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "充值的钻石记录"
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        loadFirst()
    }
}

extension MTTopUpHistoryListController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTTopUpHistoryListController {
    
    private func redPacketListController(didClickContactButton sender: UIButton) {
        
    }
    
    
}

extension MTTopUpHistoryListController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: TopUpHistoryListCell.reuseIdentity(), for: indexPath) as! TopUpHistoryListCell
        if result.count > indexPath.row {
        
            cell.model = self.result[indexPath.row]
//            cell.isSend = isSend
        }
        return cell
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 84
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}
